from fastapi import HTTPException, status

from app.models.users import User
from app.schemas.users import UserCreateSchema, UserUpdateSchema


async def get_user_by_email(email: str) -> User | None:
    return await User.filter(email=email).first()


async def get_user_by_id(user_id: int) -> User | None:
    return await User.get_or_none(id=user_id)


async def create_user(user_schema: UserCreateSchema, enabled: bool = False) -> User:
    user_dict = user_schema.model_dump(exclude_unset=True)
    user_dict["hashed_password"] = user_dict.pop("password")
    if enabled:
        user_dict["disabled"] = False
    new_user = User(**user_dict)
    await new_user.save()
    return new_user


async def update_user(user: User, user_schema: UserUpdateSchema) -> User:
    user_dict = user_schema.model_dump(exclude_unset=True)
    if user_dict.get("password"):
        user_dict["hashed_password"] = user_dict.pop("password")
    await user.update_from_dict(user_dict)
    await user.save()
    return user


async def get_users(offset: int = 0, limit: int = 40) -> list[User]:
    # Return all users without "doctor" related model
    return await User.filter(doctor__isnull=True).offset(offset).limit(limit)


async def delete_user(user_id: int) -> None:
    await User.filter(id=user_id).delete()


async def verify_user(user_id: int) -> bool:
    user = await get_user_by_id(user_id)
    if user is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")

    if user.disabled:
        user.disabled = False
        await user.save()

    return True
